import { areaList } from '@vant/area-data'
import api from '../../api/api'
import Toast from '@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    tel: '',
    addressDetail: '',
    areaName: '',
    areaCode: '',
    postalCode: '',
    show: false,
    areaList,
    isDefault: 0,
    province: '',
    city: '',
    county: '',
  },
  showArea() {
    this.setData({
      show: true
    })
  },
  hideArea() {
    this.setData({
      show: false
    })
  },
  onConfirm(val) {
    let names = []
    val.detail.values.forEach((v) => {
      names.push(v.name)
    })
    this.setData({
      province: names[0],
      city: names[1],
      county: names[2]
    })
    names = names.join(' ')
    this.setData({
      areaName: names,
      areaCode: val.detail.values[2].code,
      show: false
    })
  },
  defaultChange(e) {
    console.log(e.detail);
    this.setData({
      isDefault: e.detail
    })
  },
  async add(e) {
    let areaCode = this.data.areaCode
    let province = this.data.province
    let city = this.data.city
    let county = this.data.county
    let tokenString = wx.getStorageSync('token')
    let name = e.detail.value.name
    let tel = e.detail.value.tel
    let addressDetail = e.detail.value.addressDetail
    let postalCode = e.detail.value.postalCode
    let isDefault = this.data.isDefault
    if (name == '') {
      Toast.fail('请填写姓名')
      return
    }
    const ruleRegPhone = /^1[3-9]\d{9}$/
    if (tel == '') {
      Toast.fail('请填写电话')
      return
    }
    if (!ruleRegPhone.test(tel)) {
      Toast.fail('联系电话格式有误')
      return
    }
    if (areaCode == '') {
      Toast.fail('请选择地区')
      return
    }
    if (addressDetail == '') {
      Toast.fail('请填写详细地址')
      return
    }
    if (postalCode == '') {
      Toast.fail('请填写邮政编码')
      return
    }
    const res = await api.addAddress({ tokenString, province, city, county, name, tel, addressDetail, postalCode, isDefault, areaCode })
    if (res.data.code == 9000) {
      console.log('新增地址', res)
      Toast.success(res.data.msg)
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})